package util

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/chromedp/chromedp"

	//	"fmt"
	"go-chromedp-client/structs"
	"io/ioutil"
	//"strings"
)

func OcrDom(contxt context.Context, cap string) (string, error) {
	//获取base64
	var res []byte
	caps := strings.Split(cap, ">")
	fmt.Println("OcrDom 22 ", caps)
	chromedp.Run(contxt, chromedp.Screenshot(caps[0], &res, chromedp.NodeVisible))
	//fmt.Println("base64", res, base64.StdEncoding.EncodeToString(res))
	text, err := CaptchaBase64Text(base64.StdEncoding.EncodeToString(res))
	if len(caps) > 1 {
		fmt.Println("OcrDom var " + text)
		chromedp.Run(contxt,
			chromedp.EvaluateAsDevTools(`localStorage.setItem("`+caps[1]+`","`+text+`")`, nil),
		)
	}
	return text, err
}

func CaptchaFileText(imgPath string) (string, error) {
	fr, err := ioutil.ReadFile(imgPath)
	if err != nil {
		return "", err
	}

	base64str := base64.StdEncoding.EncodeToString(fr)
	return CaptchaBase64Text(base64str)
	//fmt.Println(string(out), err)

}
func CaptchaBase64Text(base64str string) (string, error) {
	api := "http://127.0.0.1:1224/api/ocr"
	op := structs.Options{}
	header := *&[]string{"Content-Type:application/json"}
	out, err := Post(api, header, `{"base64":"`+base64str+"123123"+`","options":{}}`, op)
	if err != nil {
		return "", err
	}
	var dat structs.OcrData
	json.Unmarshal([]byte(out), &dat)
	if dat.Code != 100 {
		return out, nil
	}
	//fmt.Println(out, err)
	return dat.Data[0].Text, nil
}
